package com.coollang.smartbra.fragment;

import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.andexert.library.RippleView;
import com.coollang.smartbra.R;
import com.coollang.smartbra.activity.MainActivity;
import com.coollang.smartbra.base.BaseFragment;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.dialog.ShareBitmapDialog;
import com.coollang.smartbra.utils.ActivitySwitcher;
import com.coollang.smartbra.utils.FormatUtils;
import com.coollang.smartbra.utils.ShareUtils;
import com.coollang.smartbra.utils.TextStyleUtils;
import com.coollang.smartbra.utils.TimeUtils;
import com.coollang.smartbra.utils.ToastUtils;
import com.coollang.smartbra.utils.TranslucentSystemBarUtils;
import com.coollang.smartbra.utils.UIUtils;
import com.coollang.smartbra.views.RoundProgressBarWidthNumber;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.sweetalert.SweetAlertDialog;

/**
 * 环境页面
 */

public class EnFragment extends BaseFragment implements RippleView.OnRippleCompleteListener {

    private static final String TAG = "EnFragment";
    @BindView(R.id.status_bar)
    View statusBar;
    @BindView(R.id.tv_title_realtime)
    TextView tvTitleRealtime;
    @BindView(R.id.imgv_device_right)
    ImageView imgvDeviceRight;
    @BindView(R.id.tv_temp)
    TextView tvTemp;
    @BindView(R.id.tv_shidu)
    TextView tvShidu;
    @BindView(R.id.tv_co2)
    TextView tvCo2;
    @BindView(R.id.iv_jiaquan)
    TextView ivJiaquan;
    @BindView(R.id.tv_ziwaixian)
    TextView tvZiwaixian;
    @BindView(R.id.rl_temp)
    RelativeLayout rlTemp;
    @BindView(R.id.rl_shidu)
    RelativeLayout rlShidu;
    @BindView(R.id.rl_co2)
    RelativeLayout rlCo2;
    @BindView(R.id.rl_yichun)
    RelativeLayout rlYichun;
    @BindView(R.id.rl_jiaquan)
    RelativeLayout rlJiaquan;
    @BindView(R.id.rl_ziwaixian)
    RelativeLayout rlZiwaixian;
    @BindView(R.id.rl_top_realtime)
    RelativeLayout rlTopRealtime;
    @BindView(R.id.top)
    LinearLayout top;
    @BindView(R.id.tv_yichun)
    TextView tvYichun;
    @BindView(R.id.tv_jiaquan)
    TextView tvJiaquan;
    @BindView(R.id.content)
    LinearLayout content;
    @BindView(R.id.iv_calendar_realtime)
    ImageView ivCalendarRealtime;
    @BindView(R.id.rv_back)
    RippleView rvBack;
    @BindView(R.id.rv_share)
    RippleView rvShare;

    @BindView(R.id.tv_en_strength)
    TextView mTvStrength;
    @BindView(R.id.enfragment_time)
    TextView mTvTime;
    @BindView(R.id.tv_ble_disconnect)
    TextView mTvBleDisConnect;
    @BindView(R.id.progress_bar)
    RoundProgressBarWidthNumber mProgressBar;

    @BindView(R.id.en_weather_count)
    TextView mTvEnWeatherCount;
    @BindView(R.id.en_weather_count_symbol)
    TextView mTvEnWeatherCountSymbol;
    @BindView(R.id.rl_en_weather)
    RelativeLayout mReEnWeather;
    @BindView(R.id.ll_countdown_1)
    LinearLayout mLlCountDown1;
    @BindView(R.id.ll_countdown_2)
    LinearLayout mLlCountDown2;

    private View view;
    private float mJiaquan;

    //弹窗
    SweetAlertDialog mShowStateDialog;
    private CountDownTimer mCountDownTimer;

    @Override
    public View inflateView(LayoutInflater inflater) {
        view = inflater.inflate(R.layout.fragment_en, null, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void initView(View view) {
        // EventBus.getDefault().register(this);
        TranslucentSystemBarUtils.showChenJinZhuangTaiLan(statusBar);
        findViewByids();
        initCountDown();

        setDefalutDisPlay();

        Typeface typeFace = Typeface.createFromAsset(getActivity().getAssets(), "fonts/enfragment_type.ttf");
        //设置字体
        mTvTime.setTypeface(typeFace);
        mProgressBar.setAngle();
        mProgressBar.setColor(0x00000000, 0xFFF0FD60);
    }


    /**
     * 初始化倒计时
     */
    private void initCountDown() {
        mCountDownTimer = new CountDownTimer(181000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // 三分钟倒计时开始
                mTvTime.setText(TimeUtils.getFormatTimemmss(millisUntilFinished / 1000) + "");
            }

            @Override
            public void onFinish() {
                // 倒计时结束 切换UI展示
                hideCountDownTime();
                timeIsStart = false;
            }
        };
    }

    /**
     * 设置progressbar进度条
     */
    private void setProgressBar(int progress) {
        mProgressBar.setProgress(progress);
        mTvEnWeatherCount.setText(progress + "");
    }

    public void onEnMeasureDataRecieved(int tempState, int temp, int shidu, int ziwaixian) {
        setHasDataDisplay(tempState, temp, shidu, ziwaixian);
    }

    public void onVOCMeasureStart(byte b) {
        if (b == (byte) 0x00) {
            // 开始
            showMeasureDialog();
        } else if (b == (byte) 0x01) {
            // 在充电,不可进行VOC测量
            showStateDialog(UIUtils.getString(R.string.charging_tips));
        }
    }

    public void onVOCMeasureData(int jiaquan, int tvoc, int co2) {
        mJiaquan = FormatUtils.formatFloat3Tofloat((jiaquan * 1.34f) / (float) 100);

        //甲醛
        tvJiaquan.setText(TextStyleUtils.setTextStyle(mJiaquan + "", mJiaquan + " " + UIUtils.getString(R.string.unit_jiaquan), 16, UIUtils.getColor(R.color.black_80)));
        //co2
        tvCo2.setText(TextStyleUtils.setTextStyle(co2 + "", co2 + " " + UIUtils.getString(R.string.unit_co2), 16, UIUtils.getColor(R.color.black_80)));

        tvYichun.setText(TextStyleUtils.setTextStyle(tvoc + "", tvoc + " " + UIUtils.getString(R.string.tvo), 16, UIUtils.getColor(R.color.black_80)));
    }

    /**
     * 显示正在采集数据弹窗
     */
    private void showMeasureDialog() {
        // 开始倒计时
        countDownStart();
    }

    /**
     * 有数据显示
     */
    private void setHasDataDisplay(int tempState, int temp, int shidu, int ziwaixian) {
        if (UIUtils.getString(R.string.gang).equals(tvTemp.getText().toString())) {
            setSelect(0, temp + "");
        }

        //温度
        if (tempState == 0) {
            //正值
            tvTemp.setText(TextStyleUtils.setTextStyle(temp + "", temp + " " + UIUtils.getString(R.string.unit_temp), 16, UIUtils.getColor(R.color.black_80)));
        } else {
            //负值
            tvTemp.setText(TextStyleUtils.setTextStyle("-" + temp + "", "-" + temp + " " + UIUtils.getString(R.string.unit_temp), 16, UIUtils.getColor(R.color.black_80)));
        }

        showEbBleConnectView();

        //湿度
        tvShidu.setText(TextStyleUtils.setTextStyle(shidu + "", shidu + " " + UIUtils.getString(R.string.unit_baifenhao1), 16, UIUtils.getColor(R.color.black_80)));
        //紫外线
        tvZiwaixian.setText(TextStyleUtils.setTextStyle(ziwaixian + "", ziwaixian + " " + UIUtils.getString(R.string.symbol), 16, UIUtils.getColor(R.color.black_80)));
    }

    private void showStateDialog(String tipStr) {
        if (mShowStateDialog == null) {
            showStateDialogTwo(tipStr);
        } else {
            if (mShowStateDialog.isShowing()) {
                mShowStateDialog.dismiss();
            }
            showStateDialogTwo(tipStr);
        }
    }

    private void showStateDialogTwo(String tipStr) {
        mShowStateDialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.NORMAL_TYPE);
        mShowStateDialog.setTitleText(tipStr)
                .setConfirmText(getString(R.string.ok))
                .showCancelButton(false)
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                    }
                });
        mShowStateDialog.show();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (hidden) {
            // fragmeng 不可见了
            ((MainActivity) getActivity()).setEnFragmengBleCommand(2);
            // 将那几个数 重置为--
            resetData();
        } else {
            setDefalutDisPlay();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        ((MainActivity) getActivity()).setEnFragmengBleCommand(1);
    }

    private void resetData() {
        tvCo2.setText(UIUtils.getString(R.string.gang));
        tvJiaquan.setText(UIUtils.getString(R.string.gang));
        tvYichun.setText(UIUtils.getString(R.string.gang));

        tvZiwaixian.setText(UIUtils.getString(R.string.gang));
    }


    /**
     * 无数据显示
     */
    private void setDefalutDisPlay() {
        //未连接状态
        if (!MyApplication.getApplication().isConnected) {
            showGo();
            showEbBleDisConnectView();

            rlTemp.setSelected(false);

            tvTemp.setText(UIUtils.getString(R.string.gang));
            tvShidu.setText(UIUtils.getString(R.string.gang));
            tvCo2.setText(UIUtils.getString(R.string.gang));
            tvYichun.setText(UIUtils.getString(R.string.gang));
            tvJiaquan.setText(UIUtils.getString(R.string.gang));
            tvZiwaixian.setText(UIUtils.getString(R.string.gang));
        } else {
            //同步上传测量数据显示
            showEbBleConnectView();
            ((MainActivity) getActivity()).setEnFragmengBleCommand(1);
        }
    }

    private void findViewByids() {
        rvBack.setVisibility(View.GONE);

        rvShare.setOnRippleCompleteListener(this);
        imgvDeviceRight.setBackgroundResource(R.drawable.icon_share);
        tvTitleRealtime.setText(getString(R.string.app_en));
        tvTitleRealtime.setTextColor(UIUtils.getColor(R.color.black_666));
    }

    /**
     * 去测环境
     */
    private void goToEn() {

        if (!MyApplication.getApplication().isConnected) {
            ToastUtils.showToast(UIUtils.getString(R.string.ble_disconnect));
        } else {
            //环境测量
            if (!timeIsStart) {
                ((MainActivity) getActivity()).setEnFragmengBleCommand(3);
            }
        }
    }

    @Override
    public void onDestroy() {
        // EventBus.getDefault().unregister(this);
        countDownCancel();
        super.onDestroy();
    }

    private void showGo() {

        AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
        dialog.setMessage(getString(R.string.ble_disconnect1));
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.cancel1), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 点击事件的回调方法
                ((MainActivity) getActivity()).menu_frist.setChecked(true);
            }
        });

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.go_connect), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ActivitySwitcher.goSearchAct(getActivity());
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        Button posiviveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        posiviveButton.setTextColor(Color.parseColor("#F79444"));
        Button negativeButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        negativeButton.setTextColor(Color.parseColor("#000000"));
    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.rl_temp, R.id.rl_shidu, R.id.rl_co2, R.id.rl_yichun, R.id.rl_jiaquan, R.id.rl_ziwaixian})
    public void onClick(View view) {
        if (!MyApplication.getApplication().hasConnected()) {
            return;
        }

        switch (view.getId()) {
            case R.id.rl_temp:
                String temp = tvTemp.getText().toString();
                if (!UIUtils.getString(R.string.gang).equals(temp)) {
                    // 选中该 然后设置progress
                    String[] split = temp.split(UIUtils.getString(R.string.unit_temp));
                    setSelect(0, split[0].trim());
                }
                break;
            case R.id.rl_shidu:
                String shidu = tvShidu.getText().toString();
                if (!UIUtils.getString(R.string.gang).equals(shidu)) {
                    String[] split = shidu.split(UIUtils.getString(R.string.unit_baifenhao1));
                    setSelect(1, split[0].trim());
                }
                break;
            case R.id.rl_co2:
                String co2 = tvCo2.getText().toString();
                if (!UIUtils.getString(R.string.gang).equals(co2)) {
                    // 二氧化碳
                    String[] split = co2.split(UIUtils.getString(R.string.unit_co2));
                    setSelect(4, split[0].trim());
                } else {
                    // 开启倒计时
                    goToEn();
                }
                break;
            case R.id.rl_yichun:
                // TVO
                String tVoc = tvYichun.getText().toString();
                if (!UIUtils.getString(R.string.gang).equals(tVoc)) {
                    // 甲醛
                    String[] split = tVoc.split(UIUtils.getString(R.string.tvo));
                    setSelect(3, split[0].trim());
                } else {
                    // 开启倒计时
                    goToEn();
                }

                break;
            case R.id.rl_jiaquan:
                String jiaquan = tvJiaquan.getText().toString();
                if (!UIUtils.getString(R.string.gang).equals(jiaquan)) {
                    // 甲醛
                    String[] split = jiaquan.split(UIUtils.getString(R.string.unit_jiaquan));
                    setSelect(5, split[0].trim());
                } else {
                    // 开启倒计时
                    goToEn();
                }
                break;
            case R.id.rl_ziwaixian:
                String ziwaixian = tvZiwaixian.getText().toString();
                if (!UIUtils.getString(R.string.gang).equals(ziwaixian)) {
                    String[] split = ziwaixian.split(UIUtils.getString(R.string.symbol));
                    setSelect(2, split[0].trim());
                }
                break;
            default:
                break;
        }
    }

    private void setSelect(int selectID, String s) {

        rlTemp.setSelected(false);
        rlShidu.setSelected(false);
        rlZiwaixian.setSelected(false);
        rlYichun.setSelected(false);
        rlCo2.setSelected(false);
        rlJiaquan.setSelected(false);

        switch (selectID) {
            case 0:
                rlTemp.setSelected(true);
                mProgressBar.setMax(60);
                int temp = Integer.parseInt(s);
                setProgressBar(temp);
                signTemp(temp);
                mTvEnWeatherCountSymbol.setText(UIUtils.getString(R.string.unit_temp));
                break;
            case 1:
                mProgressBar.setMax(100);
                rlShidu.setSelected(true);
                int shidu = Integer.parseInt(s);
                setProgressBar(shidu);
                signShidu(shidu);
                mTvEnWeatherCountSymbol.setText(UIUtils.getString(R.string.unit_baifenhao1));
                break;
            case 2:
                mProgressBar.setMax(250);
                rlZiwaixian.setSelected(true);
                int ziwaixian = Integer.parseInt(s);
                setProgressBar(ziwaixian);
                signZiwaixian(ziwaixian);
                mTvEnWeatherCountSymbol.setText(UIUtils.getString(R.string.symbol));
                break;
            case 3:
                mProgressBar.setMax(840);
                rlYichun.setSelected(true);
                int tvoc = Integer.parseInt(s);
                setProgressBar(tvoc);
                signTvoc(tvoc);
                mTvEnWeatherCountSymbol.setText(UIUtils.getString(R.string.tvo));
                break;
            case 4:
                mProgressBar.setMax(3000);
                rlCo2.setSelected(true);
                int co2 = Integer.parseInt(s);
                setProgressBar(co2);
                signCo2(co2);
                mTvEnWeatherCountSymbol.setText(UIUtils.getString(R.string.unit_co2));
                break;
            case 5:
                mProgressBar.setMax(600);
                rlJiaquan.setSelected(true);
                float jiaquan = Float.parseFloat(s);
                setProgressBar((int) (jiaquan * 100));
                signJiaquan(jiaquan);
                mTvEnWeatherCount.setText(jiaquan + "");
                mTvEnWeatherCountSymbol.setText(UIUtils.getString(R.string.unit_jiaquan));
                break;
            default:
                break;

        }
    }

    /**
     * 去刷新环境
     */
    private void toRefreshEN() {
        showCountDownTime();
    }

    @Override
    public void onComplete(RippleView rippleView) {
        switch (rippleView.getId()) {
            case R.id.rv_share:
                // 分享此页面
                startShare();
        }
    }

    /**
     * 判断时间倒计时是否开始
     */
    public boolean timeIsStart = false;

    private void countDownStart() {
        if (!timeIsStart) {
            mCountDownTimer.start();
            timeIsStart = true;
            toRefreshEN();
        }
    }

    private void countDownCancel() {
        if (timeIsStart) {

            ((MainActivity) getActivity()).setEnFragmengBleCommand(4);
            mCountDownTimer.cancel();
            timeIsStart = false;
        }
    }

    /**
     * 显示蓝牙连接之后环境页面对应的布局
     */
    private void showEbBleConnectView() {
        mTvBleDisConnect.setVisibility(View.GONE);
        mTvEnWeatherCount.setVisibility(View.VISIBLE);
        mTvEnWeatherCountSymbol.setVisibility(View.VISIBLE);
        mTvStrength.setVisibility(View.VISIBLE);
    }

    /**
     * 显示蓝牙未连接对应的布局
     */
    private void showEbBleDisConnectView() {
        mTvBleDisConnect.setVisibility(View.VISIBLE);
        mTvEnWeatherCount.setVisibility(View.INVISIBLE);
        mTvEnWeatherCountSymbol.setVisibility(View.INVISIBLE);
        mTvStrength.setVisibility(View.INVISIBLE);

        mProgressBar.setProgress(0);
    }

    /**
     * 显示三分钟倒计时布局
     */
    private void showCountDownTime() {
        mReEnWeather.setVisibility(View.GONE);
        mLlCountDown1.setVisibility(View.VISIBLE);
        mLlCountDown2.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏三分钟倒计时布局
     */
    private void hideCountDownTime() {
        mReEnWeather.setVisibility(View.VISIBLE);
        mLlCountDown1.setVisibility(View.GONE);
        mLlCountDown2.setVisibility(View.GONE);
    }

    /**
     * 解析温度数据
     */
    private void signTemp(int temp) {
        String sign = "";
        if (temp < 18) {
            sign = "较低";
        } else if (18 <= temp && temp <= 25) {
            sign = "舒适";
        } else if (temp > 25) {
            sign = "较高";
        }
        mTvStrength.setText(sign);
    }

    /**
     * 解析湿度数据
     */
    private void signShidu(int shidu) {
        String sign = "";
        if (shidu < 40) {
            sign = "干燥";
        } else if (40 <= shidu && shidu <= 60) {
            sign = "舒适";
        } else if (shidu > 60) {
            sign = "较高";
        }

        mTvStrength.setText(sign);
    }

    /**
     * 解析紫外线数据
     */
    private void signZiwaixian(int ziwaixian) {
        String sign = "";

        if (ziwaixian >= 0 && ziwaixian <= 2) {
            sign = "最弱";
        } else if (ziwaixian >= 3 && ziwaixian <= 4) {
            sign = "弱";
        } else if (ziwaixian >= 5 && ziwaixian <= 6) {
            sign = "适中";
        } else if (ziwaixian >= 7 && ziwaixian <= 9) {
            sign = "强";
        } else if (ziwaixian >= 10) {
            sign = "很强";
        }
        mTvStrength.setText(sign);
    }

    /**
     * 解析甲醛数据
     */
    private void signJiaquan(float jiaquan) {
        String sign = "";

        if (jiaquan <= 0.1f) {
            sign = "正常";
        } else if (jiaquan > 0.1f && jiaquan <= 0.3f) {
            sign = "轻度污染";
        } else if (jiaquan > 0.3f) {
            sign = "超标";
        }

        mTvStrength.setText(sign);
    }

    /**
     * 解析二氧化碳数据
     */
    private void signCo2(int co2) {
        String sign = "";
        if (co2 <= 1000) {
            sign = "正常";
        } else if (co2 > 1000 && co2 <= 2000) {
            sign = "轻度污染";
        } else if (co2 > 2000) {
            sign = "超标";
        }

        mTvStrength.setText(sign);
    }

    /**
     * 解析二氧化碳数据
     */
    private void signTvoc(int tvoc) {
        String sign = "";
        if (tvoc <= 280) {
            sign = "优";
        } else if (tvoc > 280 && tvoc <= 560) {
            sign = "中";
        } else if (tvoc > 560) {
            sign = "差";
        }
        mTvStrength.setText(sign);
    }

    /**
     * app点击退出测量了
     */
    public void dropOutMeasuring() {
        countDownCancel();
        hideCountDownTime();
    }

    // =============================== 分享 ===================================

    private ShareUtils mShareUtils;
    private ShareBitmapDialog mShareBitmapDialog;

    // 开始分享
    private void startShare() {
        // 截取屏幕

        if (mShareUtils == null) {
            mShareUtils = new ShareUtils(getActivity());
            mShareBitmapDialog = new ShareBitmapDialog(getContext(), null);
            mShareBitmapDialog.setOnclickListener(mOnclickListener);
        }
        mShareUtils.initShare();
        mShareBitmapDialog.show();
    }

    private ShareBitmapDialog.OnclickListener mOnclickListener = new ShareBitmapDialog.OnclickListener() {
        @Override
        public void onCancel() {
            mShareBitmapDialog.dismiss();
        }

        @Override
        public void onWeixin() {
            mShareUtils.share(1);
        }

        @Override
        public void onWEXIN_CIRCLE() {
            mShareUtils.share(2);
        }

        @Override
        public void onWeibo() {
            mShareUtils.share(3);
        }

        @Override
        public void onQQ() {
            mShareUtils.share(4);
        }
    };
}
